import { json } from "@sveltejs/kit";
import { comparePassword } from "$lib/utils/password";
import usersModule from "$lib/modules/users";
import jwt from "$lib/utils/jwt";
import { LOGIN_COOKIE_CONFIG, AUTH_TOKEN } from "$lib/config/variable";
import permissionsModule from "$lib/modules/permissions";
import { generateCurrentUserRoutesAndApis } from "$lib/utils/generateRoutesAndApis";

export async function POST({ request, cookies }) {
  const { username, password } = await request.json();
  if (!username || !password) { return json({ message: "用户名或密码不能为空", status: false }, { status: 400 }); }
  const user = await usersModule.getByUsername(username);
  if (!user) { return json({ message: "用户不存在" }, { status: 400 }); }
  const isPasswordValid = await comparePassword(password, user.password);
  if (!isPasswordValid) { return json({ message: "密码错误", status: false }, { status: 400 }); }
  let permissions = { routes: [], apis: [], handles: [] };
  if (!!user.role_id) {
    const currentUserPermissions = (await permissionsModule.getByRoleId(user.role_id))?.permissions;
    const handles = currentUserPermissions.map(handle => handle.handle);
    permissions = await generateCurrentUserRoutesAndApis(handles);
  }
  const token = await jwt.generate({ id: user.id, username: user.username, permissions });
  cookies.set(AUTH_TOKEN, token, LOGIN_COOKIE_CONFIG);
  return json({ message: "登录成功", status: true }, { status: 200 });
}
